<template>
  <div :class="className" :style="{height:height,width:width}" ref="chartDiv"/>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils'
import walden from "./theme/walden.json";
import html2canvas from "html2canvas";

const animationDuration = 6000

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    optionTitleText: {
      type: String,
      default: ''
    },
    optionLegend:{
      type: Array,
      default: []
    },
    optionSeries:{
      type: Array,
      default: []
    },
    optionXAxisData:{
      type: Array,
      default: []
    },
    saveImage: {
      type: Boolean,
      default: false
    },
    subtext: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      base64Image: undefined,
      chart: null,
      opinion:{
        toolbox: {
          feature: {
            saveAsImage: {},
            // myExport: {
            //   show: true,
            //   title: '导出xls',
            //   icon: 'image://',
            //   onclick: function (){
            //
            //   }
            // },
            myStyle: {
              show: true,
              title: '切换显示',
              icon: 'image://',
              onclick: this.OnclickHandle
            },

          }
        },
        title: {
          text: this.optionTitleText,
          subtext:this.subtext,
          padding: 10,
        },
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        dataZoom:[
          {
            type:'slider',
            show:true,
            start:0,//数据窗口范围的起始百分比,表示1%
            end:100//数据窗口范围的结束百分比,表示1%坐标
          }
        ],
        legend: {
          top:"10%",
          data: this.optionLegend
        },
        grid: {
          top: 60,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          data: this.optionXAxisData,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: this.optionSeries
      }
    }
  },
  watch:{
    optionSeries(newValue,oldValue){
      this.opinion.series=newValue
      this.chart.setOption(this.opinion);
    },
    optionXAxisData(newValue,oldValue){
      this.opinion.xAxis[0].data=newValue
      this.chart.setOption(this.opinion);
    },
    optionLegend(newValue,oldValue){
      this.opinion.legend.data=newValue
      this.chart.setOption(this.opinion);
    },
    optionTitleText(newValue,oldValue){
      this.opinion.title.text=newValue
      this.chart.setOption(this.opinion);
    },
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    OnclickHandle(){
      this.optionSeries.forEach(item=>{
        if(item.type=='line'){
          item.type='bar'
        }else if(item.type=='bar'){
          item.type='line'
        }
      })
      this.chart.setOption(this.opinion);
    },
    doSaveImage(){
      let element = this.$refs.chartDiv
      const p1 = new Promise((resolve, reject) => {
        html2canvas(element).then(canvas => {
          this.base64Image = canvas.toDataURL("image/png")
          this.$emit("getBase64Image",this.base64Image)
          resolve()
        }).catch(error => {
          reject(error)
        });
      })
      const p = Promise.all([p1]);
      p.then(res => {

      })

    },
    initChart() {
      echarts.registerTheme('walden', walden)
      this.chart = echarts.init(this.$el, 'walden')
      this.chart.setOption(this.opinion)
      this.chart.on('finished',() => {
        if(this.saveImage){
          this.doSaveImage();
        }
      })
      this.chart.on('click', param => {
        this.$emit('clickEvent', {x:param.name,y:param.value,name:this.opinion.series[param.seriesIndex].name})
      })
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHandler)
    }
  }
}
</script>
